package com.mud.ultimate.tasks;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

public class AsyncTaskUploadScore extends AsyncTask<String, Void, String> {

	public interface UploadCompleteListener {
		   public void onTaskComplete(String aResult);
		   public void onError(String aError);
	}
	
	private Context context = null;
	private ProgressDialog progressDialog = null;
	private UploadCompleteListener listener;
	private String error = null;
	private String name;
	private int score;

	public AsyncTaskUploadScore(Context context, UploadCompleteListener aListener, String name, int score) {
	    this.context = context; 
	 
	    listener = aListener;
		this.name = URLEncoder.encode(name);
		this.score = score;
	}
	
	@Override
	protected void onPreExecute() {
		progressDialog = new ProgressDialog(this.context);
	    progressDialog.setMessage("Uploading score...");
	    progressDialog.show();
	}
	
	@Override
	protected String doInBackground(String... params) {
		
		BufferedReader reader = null;
		String result = "";
		try {
			URL url = new URL("http://meadmin-mudstudio.rhcloud.com/rest/Score/submit?name="+name+"&score="+score);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			
			String line = "";
			while ((line = reader.readLine()) != null) {
				result += line;
			}
			if(!result.equals("OK"))
			{
				error=result;
			}
			
			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	
		
		return result;
	}
	
	@Override
	protected void onPostExecute(String result) {
	    progressDialog.dismiss();
	    if (error != null) {
	    	listener.onError(error);
	    }
	    else {
	    	listener.onTaskComplete(result);
	    }
	}
}